import React, {Component} from 'react'
import {
  View,
  Text,
  StyleSheet,
  Platform,
  TouchableOpacity,
  Image,
  ListView,
  Animated,
  Dimensions,
  TextInput,
  Alert,
  ActivityIndicator,
} from 'react-native'
import {SearchBar, List, ListItem, Icon} from 'react-native-elements'
import colors from './../../styles/colors'
import font from './../../styles/font'
import FlatListBasic from './../../../app/components/common/FlatListBasic'
import ICON from 'react-native-vector-icons/Ionicons'
import {Actions} from "react-native-router-flux";
import { SafeAreaView } from 'react-navigation';

import Toast, {
  DURATION
} from 'react-native-easy-toast'
import * as stringUtils from './../../utils/srting'
import * as UKD from './../../services/userKeyword'
import {contains} from  './../../utils/arrays'

const {
  height: deviceHeight,
  width: deviceWidth
} = Dimensions.get("window");

const pattern = new RegExp("￥")

class ListsScene extends Component {
  constructor(props) {
    super(props)
    this.ds = new ListView.DataSource({
      rowHasChanged: (r1, r2) => r1 !== r2
    });
    this.state = {
      dataSource: this.ds.cloneWithRows([]),
      dataKeyword: [],
      sort: 'sort',
      keyword: '',
      startPrice: 0,
      endPrice: 0,
      selectData: [
        {name: '综合', data: 'sort'},
        {name: '商场', data: 'isTmall'},
        {name: '销量', data: 'hot'},
        {name: '价格', data: 'price'},
      ],
      top: new Animated.Value(0),
      priceSelectStatus: false,
      searchModalStatus: false,
      searchInputBack: '返回',
      isRemoveKeyword: false,
      goodsListLoading: true,
      priceSort: 'price_asc'
    }

    this._show = this._show.bind(this)
    this.renderRow = this.renderRow.bind(this)
  }

  componentDidMount() {
    if(this.props.searchModal){
      this.setSearchModal(true)
      // this.search.focus()
    }else{
      this.setGoodLoading(false)
      this.setState({
        sort:this.props.sort,
        keyword:this.props.keyword,
        startPrice: this.props.startPrice,
        endPrice: this.props.endPrice,
      })
    }
  }

  componentWillReceiveProps(nextProps) {
    const {goodsList, goodsKeyword, goodsKey} = nextProps
    if(!this.state.searchModalStatus){

      if(!pattern.test(this.state.keyword)){
        //关键词搜索
        if(this.props.goodsList !== goodsList){
          if(goodsList.error !== false){
            if(goodsList.error.status === 401){

            }

            this.toast.show(goodsList.error.message)
          }else{
            if (goodsList.isLoading) {
              // TO-DO
            }else{

              if (goodsList.data.length > 0) {
                this._setRowDataAll(false)
                if (goodsList.page === 1) {
                  this._setRows(goodsList.data);
                } else {
                  this._setRows(this._getRows().concat(goodsList.data));
                }

                this.setState({
                  dataSource: this.ds.cloneWithRows(this._getRows()),
                });
                this.setGoodLoading(false)
                this._setPage(goodsList.page);
              }else{
                this._setRowDataAll(true)
                this.toast.show('优惠产品有限的')
              }


            }
          }
        }
      }else{
        //口令搜索
        if(this.props.goodsKey !== goodsKey){
          if(goodsKey.error !== false){
            if(goodsKey.error.status === 401){

            }

            this.toast.show(goodsKey.error.message)
          }else{
            if (goodsKey.isLoading) {
              // TO-DO
            }else{
              if (goodsKey.data.length > 0) {
                Actions.taoBaoWeb({...goodsKey.data[0], resultJifen:1})
                if (goodsKey.page === 1) {
                  this._setRows(goodsKey.data);
                }

                this.setState({
                  dataSource: this.ds.cloneWithRows(this._getRows()),
                });
                this.setGoodLoading(false)
                this._setPage(goodsKey.page);
                this._setRowDataAll(true)
              }else{
                this._setRowDataAll(true)
                this.toast.show('该产品没有优惠了')
              }
            }
          }
        }
      }
    }



    if(this.props.goodsKeyword !== goodsKeyword){
      if (goodsKeyword.isLoading) {

      }else{
        if (goodsKeyword.data && goodsKeyword.data.length > 0) {
          this.setState({dataKeyword: goodsKeyword.data})
        }
      }
    }
  }


  _setPage(page) {
    this._page = page;
  }
  _getPage() {
    return this._page ? this._page : 0;
  }
  _setRows(rows) {
    this._rows = rows;
  }
  _getRows() {
    return this._rows ? this._rows : [];
  }
  _setRowDataAll(rowDataAll) {
    this._rowDataAll = rowDataAll;
  }
  _getRowDataAll() {
    return this._rowDataAll ? this._rowDataAll : false;
  }

  _show(param) {
    RNAlibcSdk.show(param, (err, info) => {
        if (!err)
          console.log(info)
        else
          console.log(err)
      }
    );
  }

  //下拉刷新
  onPullReleaseData(){
    if(!pattern.test(this.state.keyword) && Actions.currentScene === "_index"){
      this.props.actions.getGoodsList({
        page:1,
        sort:this.state.sort,
        keyword:this.state.keyword,
        startPrice: this.state.startPrice,
        endPrice: this.state.endPrice,
        priceSort: this.state.priceSort
      }) 
    }

  }

  loadMore(){ //上拉更多
    if(!this.state.searchModalStatus && !pattern.test(this.state.keyword)){
      this.props.actions.getGoodsList({
        page: this._getPage() + 1,
        sort:this.state.sort,
        keyword:this.state.keyword,
        startPrice: this.state.startPrice,
        endPrice: this.state.endPrice,
        priceSort: this.state.priceSort
      })
    }
  }

  //打开价格筛选
  openPriceSelect(status){
    Animated.spring(this.state.top, {
      toValue: status ? 35 : 0,
    }).start()
    this.setState({priceSelectStatus: status})
  }

  selectButton(data){ //选择排序
    this.setState({sort:data})
    if(!pattern.test(this.state.keyword)){
      let sort;
      if(data === 'price'){
        if(this.state.priceSort === 'price_asc'){
          this.setState({priceSort:'price_dsc'})
          sort = 'price_dsc';
        }else{
          this.setState({priceSort:'price_asc'})
          sort = 'price_asc';
        }
      }

      this.openPriceSelect(false)
      this.setGoodLoading(true)
      this.props.actions.getGoodsList({
        page:1,
        sort:data,
        keyword:this.state.keyword,
        startPrice: this.state.startPrice,
        endPrice: this.state.endPrice,
        priceSort: sort
      })
    }
  }

  //搜索关键字
  searchKeyWord(keyword){
    this.setGoodLoading(true)
    this.setState({keyword:keyword})
    this.setSearchModal(false)
    this.saveKeywordToUser(keyword)
    this.props.actions.getGoodsList({
      page:1,
      sort:this.state.sort,
      keyword:keyword,
      startPrice: this.state.startPrice,
      endPrice: this.state.endPrice,
      priceSort: this.state.priceSort
    })
  }

  //修改搜索框里的字
  searchChange(text){
    this.setSearchModal(true)
    this.setState({keyword:text})
    if(text){
      if(!pattern.test(text)){
        this.props.actions.getGoodsKeyword({'keyword':text})
      }
    }
  }

  //提交搜索内容
  submitKeyword(){
    this.setSearchModal(false)
    this.setGoodLoading(true)
    if(pattern.test(this.state.keyword)){
      this.props.actions.getGoodsKey({
        keyword: this.state.keyword
      })
    }else{
      this.saveKeywordToUser(this.state.keyword)
      this.props.actions.getGoodsList({
        page: 1,
        sort:this.state.sort,
        keyword:this.state.keyword,
        priceSort: this.state.priceSort
      })
    }
  }

  //保存搜索过的关键字
  saveKeywordToUser(keyword){
    if(keyword){
      let keywordData = UKD.getUserKeywordData() ? UKD.getUserKeywordData() : []
      if(!contains(keywordData, keyword)) {
        let ukd = keywordData.concat(keyword)
        UKD.saveUKD(ukd)
      }
    }
  }

  //打开/关闭搜索层
  setSearchModal(status){
    if(!status){
      this.search.blur();
    }
    this.setState({searchModalStatus:status, searchInputBack: status ? '取消' : '返回'})
  }

  //打开/隐藏Loading
  setGoodLoading(status){
    this.setState({goodsListLoading: status})
  }

  //删除历史关键字
  deleteUserKeyword(){
    Alert.alert(
      '确认删除全部历史记录？',
      '',
      [
        {text: '取消', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
        {text: '确定', onPress: () => {
          UKD.remUserKeywordData()
          this.setState({isRemoveKeyword: true})
          }, style: 'ok'},
      ],
      { cancelable: false }
    )
  }

  /////////////////////////////////////下面是布局模块

  // 头部搜索布局样式
  renderSearch() {
    return (
      <View style={styles.searchContainer}>
        <SearchBar
          ref={search => this.search = search}
          containerStyle={styles.search}
          inputStyle={styles.searchInput}
          round
          icon={{type: 'material', color: colors.primary, name: 'search', style: {top: 10, left: 10}}}
          clearIcon={{color: '#86939e', name: 'close', style: {top: 10, right: 10}}}
          returnKeyType="search"
          placeholder=''
          onChangeText={(text)=>{this.searchChange(text)}}
          onFocus ={()=>{this.searchChange(this.state.keyword)}}
          onClearText={()=>{this.searchChange(null)}}
          onSubmitEditing={()=>{this.submitKeyword()}}
          value={this.state.keyword}
        />
        <TouchableOpacity style={styles.backButton} onPress={() => {
          this.state.searchModalStatus && this.state.keyword ? this.setSearchModal(false) : Actions.pop()
        }}>
          <Text style={{color: '#fff'}}>{this.state.searchInputBack}</Text>
        </TouchableOpacity>
      </View>
    )
  }

  renderSelect() {// 筛选布局样式
    return (
      <View style={styles.selectContainer}>
        {
          this.state.selectData.map((e, i) => {
            let backgroundColor = e.data === this.state.sort ? {backgroundColor:colors.primary} : {backgroundColor: colors.white}
            let fontColor = e.data === this.state.sort ? font.white12 : font.black12
            let priceIcon;
            if(i === 3 && this.state.priceSort === 'price_asc'){
              priceIcon = <ICON name='md-arrow-dropup-circle' size={16}/>
            }else if(i === 3 && this.state.priceSort === 'price_dsc'){
              priceIcon = <ICON name='md-arrow-dropdown-circle' size={16}/>
            }
            return (
              <TouchableOpacity style={[styles.selectButton,backgroundColor]} key={i} onPress={()=>{this.selectButton(e.data)}}>
                {i === 1 ?
                  <Image source={require('./../../../assets/images/tmall.png')} style={styles.tMall}/> : <View></View>
                }
                <Text style={[fontColor, {justifyContent: 'center'}]}>{e.name} {priceIcon}</Text>
              </TouchableOpacity>
            )
          })
        }

      </View>
    )
  }

  renderPriceSelect(){ //价格区间筛选
    return(
      <Animated.View style={[styles.priceSelectBox, { top: this.state.top}]}>
        <Text style={{color:'#000'}}>价格</Text>
        <TextInput
          style={styles.priceInput}
          keyBoardType='numeric'
          maxLength={8}
          underlineColorAndroid='transparent'
          onChangeText={(text) => {this.setState({startPrice:text})}}
        />
        <Text>一</Text>
        <TextInput
          style={styles.priceInput}
          keyBoardType='numeric'
          maxLength={8}
          underlineColorAndroid='transparent'
          onChangeText={(text) => {this.setState({endPrice:text})}}
        />
        <TouchableOpacity style={styles.priceSubmit} onPress={()=>{
          this.setGoodLoading(false)
          this.props.actions.getGoodsList({
            page:1,
            sort:'price',
            keyword:this.state.keyword,
            startPrice: this.state.startPrice,
            endPrice: this.state.endPrice,
          })
        }}>
          <Text style={font.white12}>确定</Text>
        </TouchableOpacity>
      </Animated.View>
    )
  }

  //产品列表布局
  renderGoodsList(){
    if(this.state.goodsListLoading){
      return(
        <View style={{flex:1, justifyContent:'center', alignItems:'center'}}>
          <ActivityIndicator
            animating={true}
            size='large'
          />
        </View>
      )
    }else{
      return(
        <FlatListBasic
          dataSource={this.state.dataSource}
          renderRow={this.renderRow}
          onPullReleaseData={this.onPullReleaseData.bind(this)}
          loadMore={this.loadMore.bind(this)}
          rowDataAll={this._getRowDataAll.bind(this)}
          contentContainerStyle={{backgroundColor:'#fff'}}
          style={{backgroundColor:'#fff'}}
        />
      )
    }
  }

  renderRow(data) { //列表的单项布局样式
    let incomeratio = data.tkRate ? data.tkRate : data.incomeratio
    let jifen = ((((data.zkPrice - data.couponAmount) * ((incomeratio / 100))) * (this.props.goodsList.return_one_price / 100)) * 10)
    jifen = jifen < 0 ? 0: jifen.toFixed(2)

    let VJifen = '', vjifen= ''
    if(this.props.goodsList.data.levelRatio){
      if(this.props.goodsList.data.levelRatio !== '0'){
        vjifen = jifen * (this.props.goodsList.data.levelRatio / 100)
        VJifen = '(V+'+vjifen.toFixed(2)+')'
      }
    }else{
      if(data.levelRatio){
        if(data.levelRatio !== '0'){
          vjifen = jifen * (data.levelRatio / 100)
          VJifen = '(V+'+vjifen.toFixed(2)+')'
        }
      }
    }

    let jifenPirce = parseFloat((parseFloat(jifen) + parseFloat(vjifen ? vjifen : 0)) / 10); //最终的价格
    let resultJifen = (jifen) / 10 //最终的积分
    resultJifen = resultJifen.toFixed(2) //最终的积分

    //let itemPic = data.reservePrice === 0 ? data.pictUrl : 'http:'+data.pictUrl
    return (
      <TouchableOpacity style={styles.rowContainer} onPress={()=>{
        Actions.taoBaoWeb({...data, resultJifen})
      }}>
        {data.userType == 1  ?
        <Image source={require('./../../../assets/images/listtmall.png')} style={{position:"absolute", zIndex:99
        }}/>
        :  null
        }
        <Image
          source={{uri: data.pictUrl}}
          style={styles.rowImg}
        />
        <View style={styles.content}>
          <View style={styles.titleContainer}>
            {/*{data.userType == 1  ?*/}
              {/*<Image source={require('./../../../assets/images/tmall.png')} style={{width: 18, height: 18}}/>*/}
              {/*:  <Image source={require('./../../../assets/images/taobao.png')} style={{width: 18, height: 18}}/>*/}
            {/*}*/}

            <Text style={styles.title} numberOfLines={2}>{stringUtils.delHtmlTag(data.title)}</Text>
          </View>
          {/*{data.reservePrice !== 0 ? <Text style={styles.yuanjia}>原价￥{data.reservePrice}</Text> :*/}
            {/*<Text style={styles.qianggou}>限时抢购 <ICON name='ios-flame' size={18}/></Text>}*/}
          {this.renderItemPrice(data, jifenPirce)}
          {this.renderItemQuan(data, resultJifen, VJifen)}
        </View>
      </TouchableOpacity>
    )
  }

  renderItemPrice(data, jifenPirce){ //价格逻辑
    if(data.couponAmount === 0 || typeof(data.couponAmount) === 'undefined'){
      return(
        <Text style={{color: colors.primary, fontSize: 14}}>￥<Text
          style={{color: colors.primary, fontSize: 20, fontWeight: 'bold'}}>{data.zkPrice}</Text></Text>
      )
    }else{
      return(
        <Text style={{color: colors.primary, fontSize: 14}}>￥<Text
          style={{color: colors.primary, fontSize: 20, fontWeight: 'bold'}}>{(data.zkPrice - data.couponAmount).toFixed(2)}</Text></Text>
      )
    }
  }

  renderItemQuan(data, resultJifen, VJifen){ //券的逻辑
    if(data.couponAmount === 0 || typeof(data.couponAmount) === 'undefined'){
      return(
        <View style={styles.quanContainer}>
          <Text style={styles.quanText}>{resultJifen}元 月销{data.biz30day}件</Text>
        </View>
      )
    }else{
      return(
        <View style={styles.quanContainer}>
          <Text style={styles.quan}>券</Text><Text style={styles.quanText}>{data.couponAmount}元+{resultJifen}元{VJifen} 月销{data.biz30day}件</Text>
        </View>
      )
    }
  }

  //主要内容布局
  renderContent(){
    if(this.state.searchModalStatus && this.state.keyword && !pattern.test(this.state.keyword)){
      return(
        <List containerStyle={{marginTop:0}}>
          {
            this.state.dataKeyword.map((e, i)=>(
              <ListItem
                key={i}
                title={e}
                onPress={()=>{this.searchKeyWord(e)}}
                titleStyle={{fontSize:14, color:"#000"}}
              />
            ))
          }
        </List>
      )
    }else if((this.state.searchModalStatus && pattern.test(this.state.keyword)) || (this.state.searchModalStatus && !this.state.keyword)){
      let ukd = UKD.getUserKeywordData()
      if(ukd && ukd.length > 0){
        return(
          <View>
            <View style={styles.historyTitle}>
              <Text>历史记录</Text>
              <Icon name='ios-trash' color='#000' type='ionicon' onPress={()=>{
                this.deleteUserKeyword()
              }}/>
            </View>
            <View style={styles.historyContainer}>
              {
                ukd.map((e, i)=>{
                  return(
                    <TouchableOpacity key={i} style={styles.historyItem} onPress={()=>{this.searchKeyWord(e)}}>
                      <Text style={{color:'#000'}}>{e}</Text>
                    </TouchableOpacity>
                  )
                })
              }
            </View>
          </View>
        )
      }else{
        return null;
      }
    }else{
      return(
        <View style={{flex:1, backgroundColor:'#fff'}}>
          {this.renderSelect()}
          {this.renderPriceSelect()}
          {this.renderGoodsList()}
        </View>
      )
    }
  }

  render() {
    return (
      <SafeAreaView style={styles.container}>
        {this.renderSearch()}
        {this.renderContent()}
        <Toast
          ref={view => this.toast = view}
          style={{backgroundColor:'red'}}
          opacity={0.6}
          position='top'/>
      </SafeAreaView>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    //paddingTop: Platform.OS === 'ios' ? 20 : 0,
    backgroundColor: '#fff',
    flex: 1,
  },
  searchContainer: {
    backgroundColor: colors.primary,
    flexDirection: 'row',
    alignItems: 'center',
    zIndex: 99
  },
  search: {
    backgroundColor: colors.primary,
    flex: 1,
    borderTopColor: colors.primary,
    borderBottomColor: colors.primary,
  },
  searchInput: {
    backgroundColor: '#fff',
    height: 30,
    margin: 4,
    paddingTop: 0,
    paddingBottom: 0,
    color:'#000',
    fontSize:14
  },
  backButton: {
    width: 50,
    justifyContent: 'center',
    alignItems: 'center',
    height:40,
  },
  selectContainer: {
    height: 40,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-around',
    backgroundColor: '#ebebeb',
    zIndex: 99
  },
  selectButton: {
    backgroundColor: '#fff',
    borderRadius: 5,
    justifyContent: 'center',
    alignItems: 'center',
    width: 70,
    height: 30,
    flexDirection: 'row'
  },
  tMall: {
    width: 12,
    height: 12,
    marginRight: 5
  },
  rowContainer: {
    height: 150,
    flexDirection: 'row',
    marginHorizontal: 5,
    marginVertical: 3,
    backgroundColor: '#fff'
  },
  rowImg: {
    width: 150,
    height: 150,
    borderRadius:10
  },
  content: {
    marginLeft: 5,
    height: 100,
    flex: 1,
    paddingVertical: 2
  },
  titleContainer: {
    height: 50,
    flexDirection: 'row',
    marginTop:5,
    marginBottom: 35
  },
  title: {
    fontSize: 15,
    color: '#404040',
    marginLeft: 2,
    fontWeight: 'bold',
    marginRight:5
  },
  qianggou: {
    color: '#f00',
    fontSize: 11,
    marginVertical: 5
  },
  yuanjia: {
    fontSize: 13,
    marginVertical: 5,
    color: '#777',
    marginTop:20
  },
  quanContainer: {
    marginTop: 7,
    height: 20,
    flexDirection: 'row',
    alignItems: 'center'
  },
  quan: {
    backgroundColor: '#f50',
    color: '#fff',
    fontSize: 13,
    fontWeight: 'bold',
    textAlign: 'center',
    lineHeight: 18,
    width: 20
  },
  quanText: {
    color: '#f50',
    fontSize: 13,
  },
  webView: {
    width: 300,
    height: 370,
  },
  priceSelectBox:{
    height:40,
    borderBottomColor:'#cecece',
    borderBottomWidth:1,
    backgroundColor:'#fff',
    justifyContent:'center',
    alignItems:'center',
    position:'absolute',
    zIndex:50,
    flexDirection:'row',
    width:deviceWidth,
  },
  priceInput:{
    borderRadius:5,
    borderWidth:1,
    borderColor:'#ccc',
    width:50,
    height:25,
    marginHorizontal:5,
    paddingTop: 0,
    paddingBottom: 0
  },
  priceSubmit:{
    width:30,
    height:25,
    backgroundColor: colors.primary,
    borderRadius:5,
    justifyContent:'center',
    alignItems:'center'
  },
  historyContainer:{
    flexDirection:'row',
    flexWrap:'wrap',
    margin:10,
  },
  historyItem:{
    backgroundColor:'#f0f0f0',
    borderRadius:10,
    justifyContent:'center',
    alignItems:'center',
    margin:5,
    padding:10,
  },
  historyTitle:{
    marginTop:10,
    marginHorizontal:10,
    paddingRight:10,
    justifyContent:'space-between',
    alignItems:'center',
    flexDirection:'row'
  }
})

export const LayoutComponent = ListsScene

export function mapStateToProps(state, props) {
  return {
    routes: state.routes,
    goodsList: state.goodsListReducer,
    goodsKeyword: state.goodsKeywordReducer,
    goodsKey: state.goodsKeyReducer
  }
}